//
//  ProtocolService.m
//  healthApp
//
//  Created by william mu on 12-8-28.
//  Copyright (c) 2012年 Tencent. All rights reserved.
//

#import "ProtocolService.h"
#import "Common.h" 

NSString* get_seq()
{
    static int seq = 0;
    return [NSString stringWithFormat:@"%d", seq ++];
}


static id s_instance = nil;


#define TIME_OUT 60.0f
@interface ProtocolService(Private)
-(void) handleResult:(NSURLResponse*) response data:(NSData*)data error:(NSError*) error;
-(void) get_template:(NSString*) urlPath;
@end

@implementation ProtocolService
-(id) init
{
    if(self = [super init])
    {
        m_queue = [[NSOperationQueue alloc] init];
        
        __block ProtocolService *blocksafeSelf = self;
        m_handler = [^(NSURLResponse *response, NSData *data, NSError *error)
                     {
                         [blocksafeSelf handleResult:response data:data error:error];
                     } copy];
        
        m_request_map = [[NSMutableDictionary dictionary] retain];
    }
    
    return self;
}

-(void) logServerRes:(NSData*) data
{
    NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"server says:\n%@", str);
    [str release];
}

-(void) handleResult:(NSURLResponse*) response data:(NSData*)data error:(NSError*) error
{
    NSAssert(error == nil, @"Request error:%@", error);

    
    [self performSelectorOnMainThread:@selector(logServerRes:) withObject:data waitUntilDone:NO];
    
    
    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    
    [dict setObject:response forKey:@"response"];
    [dict setObject:data forKey:@"data"];
    if(error)
        [dict setObject:error forKey:@"error"];
    
    [self performSelectorOnMainThread:@selector(noticeResponse:) withObject:dict waitUntilDone:NO];
}

-(NSString*) extractSeq:(NSData*) data
{
    NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSArray* ary = [str componentsSeparatedByString:@"|"];
    [str release];
    return [ary objectAtIndex:0];
}

-(NSString*) extractJson:(NSData*)data
{
    NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSRange range = [str rangeOfString:@"|"];
    NSString* jsonStr = @"";
    
    if([str length] >= range.location + 1){
        jsonStr = [str substringFromIndex:range.location + 1];
    }else {
        jsonStr = @"";
    }
    
    [str release];
    
    return jsonStr;
}

-(void) noticeResponse:(NSDictionary*) responseInfo
{
    NSURLResponse* response = [responseInfo objectForKey:@"response"];
    NSData* data = [responseInfo objectForKey:@"data"];
    NSError* error = [responseInfo objectForKey:@"error"];
    
    NSAssert(error == nil, @"Request error!");
     
    NSString* seq = [self extractSeq:data];
    if(!seq)
        return;
    
    NSString* json = [self extractJson:data];
    
    NSDictionary* callBackInfo = [m_request_map objectForKey:seq];
    if(!callBackInfo)
        return;
    
    id target = [[callBackInfo objectForKey:@"target"] pointerValue];
    SEL action = [[callBackInfo objectForKey:@"action"] pointerValue];
    
    if([target respondsToSelector:action])
        [target performSelector:action withObject:json];
    
    [m_request_map removeObjectForKey:seq];
}

+(ProtocolService*) sharedInstance
{
    if(!s_instance)
        s_instance = [[ProtocolService alloc] init];
    
    return s_instance;
}

-(void) setAction:(SEL)action
{
    
    m_action = action;
}

-(void) setTarget:(id)target
{
    
    m_target = target;
}

-(NSString*) getSvrBase
{
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    NSString* svrBase = [defaults stringForKey:SVR_BASE_KEY];
    NSString* final = [NSString stringWithFormat:@"%@/index.php", svrBase];
    return final;
}

-(NSString*) loginWithUserName:(NSString*) userName password:(NSString*) password
{
    NSString* template = @"%@/login/check_customer";
    NSString* urlStr = [NSString stringWithFormat:template, [self getSvrBase]];
    NSURL* url = [NSURL URLWithString:urlStr];

    
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIME_OUT];
    NSString* seq = get_seq();
    
    NSLog(@"=>%@:%@", seq, url);
    NSString* postStr = [NSString stringWithFormat:@"tbxLoginNickname=%@&tbxLoginPassword=%@&fromiPhone=true&seq=%@", userName, password, seq];
    
    NSData* postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];

    
    NSDictionary* callBackInfo = [self getCallBackInfo];
    [m_request_map setObject:callBackInfo forKey:seq];
    m_target = nil;
    m_action = nil;
    
    [NSURLConnection sendAsynchronousRequest:request queue:m_queue completionHandler:m_handler];
    
    return seq;
}

-(void) post_template//xxxxxx
{
    
}

-(void) get_template:(NSString*) urlPath seq:(NSString*) seq
{
    NSString* urlStr = [NSString stringWithFormat:@"%@/%@", [self getSvrBase], urlPath];
    
    NSLog(@"=>%@:%@", seq, urlStr);
    
    NSURL* url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIME_OUT];

    
    NSMutableDictionary* callBackInfo = [self getCallBackInfo];
    [m_request_map setObject:callBackInfo forKey:seq];
    m_target = nil;
    m_action = nil;
    
    [NSURLConnection sendAsynchronousRequest:request queue:m_queue completionHandler:m_handler];
    
}

-(NSDictionary*) getCallBackInfo
{
    NSMutableDictionary* callBackInfo = [NSMutableDictionary dictionary];
    NSValue* targetWrap = [NSValue valueWithPointer:m_target];
    NSValue* actionWrap = [NSValue valueWithPointer:m_action];
    [callBackInfo setValue:targetWrap forKey:@"target"];
    [callBackInfo setValue:actionWrap forKey:@"action"];
    
    return callBackInfo;
}

-(NSString*) getHealthFieldMap
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_health_field_map/%@", seq];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) requestHealthInfo:(NSString*) uid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat: @"iphone_api/get_personal_health_info/%@/%@", seq, uid];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) requestMyUid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_my_uid/%@", seq];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) getFriendRequest:(NSString*) uid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_friend_request/%@/%@", seq, uid];
    
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) requestUserBaseInfo:(NSString*) uid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_base_info/%@/%@", seq, uid];
    
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) getUserFriends:(NSString*) uid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_user_friends/%@/%@", seq, uid];
    [self get_template:urlPath seq:seq];
    
    return seq;
}
-(NSString*) getSharedSymptom:(NSString*) uid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_shared_symptom/%@/%@", seq, uid];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) getSymptomMap
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_symptom_map/%@", seq];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) getAllSymptom:(NSString*) uid
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_all_symptom/%@/%@", seq, uid];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) updateHealthInfo:(NSString*) uid field:(NSString*) field value:(NSString*) value
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/update_health_info/%@/%@/%@/%@",seq, uid, field, value];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) handleFriendReq:(NSString*) req_uid accept:(NSString*)accept
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/handle_friend_req/%@/%@/%@", seq, req_uid, accept];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) updateSymptomShare:(NSString*) uid symptomType:(NSString*) symptomType  shared:(NSString*) shared
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/update_symptom_share/%@/%@/%@/%@",seq, uid, symptomType, shared];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) addSymptom:(NSString*) uid symptomType:(NSString*) symptomType shared:(NSString*) shared
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/add_symptom/%@/%@/%@/%@",seq, uid, symptomType, shared];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) deleteSymptom:(NSString*) uid symptomType:(NSString*) symptomType
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/delete_symptom/%@/%@/%@",seq, uid, symptomType];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(NSString*) getHistoryData:(NSString*) uid field:(NSString*) field
{
    NSString* seq = get_seq();
    NSString* urlPath = [NSString stringWithFormat:@"iphone_api/get_history_data/%@/%@/%@",seq, uid, field];
    [self get_template:urlPath seq:seq];
    
    return seq;
}

-(void) shutdownAnyResponse:(NSArray*) requestSeq
{
    for(NSString* seq in requestSeq)
    {
        NSLog(@"Shutdown response for:%@", seq);
        [m_request_map removeObjectForKey:seq];
    }
}
@end
